package com.genius.user.controller;

import com.genius.user.bean.dto.UserDTO;
import com.genius.user.bean.login.LoginForm;
import com.genius.user.bean.login.PhoneForm;
import com.genius.user.bean.login.RegisterForm;
import com.genius.user.service.UserService;
import com.genius.util.Common.Result;
import com.genius.util.Exception.illuminatorStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/sendCode")
    public Result sendCode(@RequestParam("phone") String phone){
        return userService.sendCode(phone);
    }

    @PostMapping("/phoneLogin")
    public Result phoneLogin(@RequestBody PhoneForm loginForm){
        return userService.phoneLogin(loginForm);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm){

        return userService.login(loginForm);
    }

    @PostMapping("/register")
    public Result register(@RequestBody RegisterForm registerForm){
        try{
          return  userService.userRegister(registerForm);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(illuminatorStatus.LoginError);
        }
    }

    @GetMapping("/userInfo")
    public Result getUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        UserDTO userDTO = userService.getUserInfo(token);
        if(userDTO==null){
            return Result.error(illuminatorStatus.LoginInvalidUser);
        }
        return Result.success(userDTO);
    }
}
